import subprocess
import time
import json

CONFIG_FILE = "config.json"
PORT = 8000
JS_FILENAME = "proxy_server.js"

def load_config():
    with open(CONFIG_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def build_proxy_js(socks5_url):
    js_code = f"""
const ProxyChain = require('proxy-chain');
const server = new ProxyChain.Server({{
    port: {PORT},
    prepareRequestFunction: () => {{
        return {{ upstreamProxyUrl: '{socks5_url}' }};
    }}
}});
server.listen(() => {{
    console.log('✅ Proxy running on http://127.0.0.1:{PORT}');
}});
"""
    with open(JS_FILENAME, "w", encoding="utf-8") as f:
        f.write(js_code)

def launch_node_proxy():
    config = load_config()
    geo = config.get("GEO", "GLOBAL")  # 默认 GLOBAL
    username = f"bluesian7_custom_zone_{geo}"
    password = "bluesian7"
    socks5 = f"socks5://{username}:{password}@us.ipwo.net:7878"

    build_proxy_js(socks5)

    # 清理旧 proxy
    subprocess.call("taskkill /f /im node.exe >nul 2>&1", shell=True)

    pass #print(f"🧱 启动新代理，使用账号: {username}")
    subprocess.Popen(["node", JS_FILENAME], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    time.sleep(2)

if __name__ == "__main__":
    launch_node_proxy()
